package dao.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import dao.BaseDao;

public abstract class BaseDaoImpl<T>  implements BaseDao<T>{
	private static String deiverName="com.mysql.jdbc.Driver";
	private String url="jdbc:mysql://localhost:3306/Delicious";
	private String userName = "root";
	private String userPwd = "root";

	//建立链接
	public Connection getconnection(){
		Connection conn = null;
		try {
			Class.forName(deiverName);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

		try {
			conn=DriverManager.getConnection(url,userName,userPwd);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}


	//关闭所有
	public void closeAll(Connection conn,Statement pstmt,ResultSet rs){
		if(rs!=null){
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		close(conn, pstmt);
	}


	public void close(Connection conn, Statement pstmt) {
		if(pstmt!=null){
			try {
				pstmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(conn!=null){
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	//查询所有
	@Override
	public List<T> showAll(String sql,Object... parms) {
		Connection conn= getconnection();
		PreparedStatement stmt=null;
		ResultSet rs=null;
		List<T> list =new ArrayList<T>();
		try {
			stmt=conn.prepareStatement(sql);
			for (int i = 0; i < parms.length; i++) {
				stmt.setObject(i+1, parms[i]);
			}
			rs=stmt.executeQuery();
			list=listByRs(rs);
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			closeAll(conn, stmt, rs);
		}
		return list;
	}
	public abstract List<T> listByRs(ResultSet rs);
	
	
	//增删改
	public void CUDObject(String sql,Object... parms){//只做增删改 create update detele
		Connection conn= getconnection();
		PreparedStatement stmt=null;
		try {
			stmt=conn.prepareStatement(sql);
			if(parms!=null&&parms.length>0){
				for (int i = 0; i < parms.length; i++) {
					stmt.setObject(i+1, parms[i]);
				}
			}
			stmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			closeAll(conn, stmt, null);
		}
	}
}
